package com.study.talk.ui.app.base

import android.app.Application
import androidx.annotation.WorkerThread
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.study.common.ToastUtil
import com.study.common.annotation.Desc
import com.study.talk.App
import com.study.talk.data.model.GroupInfo
import com.study.talk.data.model.GroupMessageRecord
import com.study.talk.data.model.MessageRecord
import com.study.talk.data.model.UserInfo
import com.study.talk.data.repository.FileRepository
import com.study.talk.data.repository.FriendRepository
import com.study.talk.data.repository.GroupRepository
import com.study.talk.data.repository.MomentRepository
import com.study.talk.data.repository.MsgRepository
import com.study.talk.data.repository.UserRepository
import com.study.talk.netty.message.response.AddUserResponse
import com.study.talk.netty.message.response.GroupMessageSelfResponse
import com.study.talk.netty.message.response.MessageSelfResponse
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
open class BaseViewModel @Inject constructor(
    application: Application
) : AndroidViewModel(application) {
    val app = application as App

    @Inject
    lateinit var userRepository: UserRepository

    @Inject
    lateinit var friendRepository: FriendRepository

    @Inject
    lateinit var groupRepository: GroupRepository

    @Inject
    lateinit var msgRepository: MsgRepository

    @Inject
    lateinit var fileRepository: FileRepository

    @Inject
    lateinit var momentRepository: MomentRepository

    fun addMsg(msg: MessageRecord) {
        msgRepository.addMsg(msg)
    }

    fun addMsg(response: MessageSelfResponse) {
        if (response.success) {
            viewModelScope.launch {
                msgRepository.addMsg(response, app.userInfo)
            }
        } else {
            ToastUtil.showToast(app, response.reason)
        }
    }

    @WorkerThread
    @Desc("创建消息并保存")
    fun addGroupMsg(response: GroupMessageSelfResponse) {
        val msg = GroupMessageRecord(
            app.userInfo, response, true
        )
        viewModelScope.launch {
            msgRepository.addMsg(msg)
        }
    }

    @WorkerThread
    @Desc("创建消息并保存")
    fun addGroupMsg(msg: GroupMessageRecord) {
        viewModelScope.launch {
            msgRepository.addMsg(msg)
        }
    }

    fun addCache(response: AddUserResponse) {
        msgRepository.addCache(response)
    }

    suspend fun getFriends(): List<UserInfo> {
        return friendRepository.getFriends()
    }

    suspend fun getGroups(): List<GroupInfo> {
        return groupRepository.getGroups(fail = {
            showToast(it)
        })
    }

    fun showToast(msg: String) {
        ToastUtil.showToast(app, msg)
    }
}